package com.caiheng.api.controller.user;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.estate.PropertyFeeOrder;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.entity.wxuser.UserIntegralRecord;
import com.caiheng.api.service.estate.EstateService;
import com.caiheng.api.service.estate.PropertyFeeOrderService;
import com.caiheng.api.service.platfom.ParameterService;
import com.caiheng.api.service.product.ProductService;
import com.caiheng.api.service.sys.SysConfigService;
import com.caiheng.api.service.wxuser.UserAddressService;
import com.caiheng.api.service.wxuser.UserIntegralRecordService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.GsonResultBean;
import com.caiheng.api.util.DateUtil;
import com.caiheng.api.util.StringUtil;
import com.caiheng.api.util.Tools;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  用户积分
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/user/integral")//url:模块/资源/{}/细分
public class UserIntegralController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private UserIntegralRecordService userIntegralRecordService;
    @Resource
    private PropertyFeeOrderService propertyFeeOrderService;
    @Resource
    private SysConfigService sysConfigService;

    /**  积分的明细列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/recordlist")
    public JSONObject recordList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "recordlist 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int inOrOut = jsonRequest.containsKey("in_or_out") ? jsonRequest.getInt("in_or_out") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") && StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 0;
            int pageSize = jsonRequest.containsKey("pageSize") && StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 20;

            QueryWrapper<UserIntegralRecord> qw= new QueryWrapper<>();
            qw.eq("user_id",user_id);
            qw.eq("in_or_out",inOrOut);

            qw.orderByDesc("create_time");
            List<UserIntegralRecord> list = userIntegralRecordService.getPageEntityList(qw,pageIndex,pageSize);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);

        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  改变选择的积分数量
     * @param
     * @throws Exception
     */
    @PostMapping(value="/changeYdCount")
    public JSONObject changeYdCount(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            Map<String,Object> map = new HashMap<>();
            logBefore(logger, "user/integral/changeYdCount 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;
            double use_integral = jsonRequest.containsKey("use_integral") ? jsonRequest.getDouble("use_integral") : 0d;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(use_integral > user.getIntegral()){
                use_integral = user.getIntegral();
            }

            map.put("payPrice",0);
            PropertyFeeOrder feeOrder = propertyFeeOrderService.findById(order_id);
            if(feeOrder!=null){
                double diKouPrice = 0;
                String diKouRate = sysConfigService.selectConfigByKey("sys.integral_rate");
                if(StrUtil.isNotEmpty(diKouRate)){
                    feeOrder.setDkRate(Integer.parseInt(diKouRate));
                    double d  = use_integral / Double.parseDouble(diKouRate);
                    diKouPrice = Double.parseDouble(String.format("%.2f",d));
                }
                feeOrder.setFreeMoney(new BigDecimal(diKouPrice));
                double payPrice = feeOrder.getTotalMoney().doubleValue() - diKouPrice;

                if(diKouPrice >= feeOrder.getTotalMoney().doubleValue()){
                    diKouPrice = feeOrder.getTotalMoney().doubleValue();
                    payPrice = 0;
                }

                feeOrder.setPayMoney(new BigDecimal(payPrice));
                String payMoneyStr = StringUtil.yuanToCent(payPrice+"");
                feeOrder.setPayMoneyFen(Integer.parseInt(payMoneyStr));
                boolean bl = propertyFeeOrderService.updateById(feeOrder);


                if(bl){
                    map.put("payPrice",payMoneyStr);
                    map.put("freeMoney",diKouPrice);
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
                }else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"失败"),true,true);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  支付积分
     * @param
     * @throws Exception
     */
    @PostMapping(value="/pay")
    public JSONObject payYueDou(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            Map<String,Object> map = new HashMap<>();
            logBefore(logger, "user/integral/changeYdCount 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int estate_id = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;
            double integral_count = jsonRequest.containsKey("integral_count") ? jsonRequest.getDouble("integral_count") : 0d;
            String remark = jsonRequest.containsKey("remark") ? jsonRequest.getStr("remark") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(integral_count > user.getIntegral()){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您的积分数量不足"),true,true);
            }

            try{
                int ret = userIntegralRecordService.costIntegral(user,estate_id,integral_count,remark);
                if(ret > 0){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"支付成功"),true,true);
                }else{
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"支付失败"),true,true);
                }
            }catch (Exception e){
                e.printStackTrace();
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"支付失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


}
